from django.contrib import messages
from django.contrib.auth import login, logout
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
import os
from io import BytesIO

from django.urls import reverse

from .forms import LoginForm, RigisterForm, SignForm
from PIL import Image, ImageDraw, ImageFont
from django import http
from django import views
from djangoProject1 import settings

# Create your views here.
from .models import User


class Login(views.View):

    def get(self, req):
        return render(req, 'login/index.html', context={'form': LoginForm()})

    def post(self, req):
        username = req.POST.get('username')
        password = req.POST.get('password')
        v_c = req.POST.get('verifycode')
        print(req.session['verifycode'], v_c)
        if req.session['verifycode'] != v_c:
            error = 'Verification code error'
        else:
            user = User.objects.filter(username=username).first()
            if not user:
                error = 'No user name'
            else:
                if not user.password == password:
                    error = 'Incorrect password'
                else:
                    login(req, user)
                    return http.HttpResponseRedirect(reverse('index'))
        return render(req, 'login/index.html', context={'form': LoginForm(), 'error': error})


def verifycode(request):
    # 引入随机函数模块
    import random
    # 定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    FONT_PATH = os.path.join(settings.BASE_DIR, 'static/font/simhei.ttf')  # 字体文件路径
    font = ImageFont.truetype(FONT_PATH, 23)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    buf = BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return http.HttpResponse(buf.getvalue(), 'image/png')


def logout_user(request):
    logout(request)
    return http.HttpResponseRedirect(reverse('mainPage'))


class Register(views.View):
    def get(self, req):
        return render(req, 'login/re_index.html', context={'form': RigisterForm()})

    def post(self, req):
        rsp = req.POST
        try:
            User.objects.create(
                username=rsp.get('username'),
                name=rsp.get('name'),
                age=rsp.get('age'),
                tel=rsp.get('tel'),
                driving_license_type=rsp.get('driving_license_type'),
                password=rsp.get('password'),
                identity_c='0'
            )

            return HttpResponse('<script>alert("Register a successful"); window.location.href = "/auth/login"</script>')
        except Exception as e:
            return HttpResponse('<script>alert("error:'+str(e)+'"); window.history.go(-1)</script>')


class Sign(views.View):

    def get(self,req):
        return render(req, 'login/sign.html', context={'form': SignForm()})

    def post(self,req):
        rsp = req.POST
        user = req.user
        try:
            user.driving_license_type = rsp.get('driving_license_type')
            user.is_buy = True
            user.save()

            return HttpResponse('<script>alert("Registration success"); window.history.go(-1)</script>')
        except Exception as e:
            return HttpResponse('<script>alert("error:'+str(e)+'"); window.history.go(-1)</script>')
